package com.xinkong.huangxunleiutils.ui.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xinkong.huangxunleiutils.R;
import com.xinkong.huangxunleiutils.base.BaseActivity;
import com.xinkong.huangxunleiutils.interfaces.ProgressResponseListener;
import com.xinkong.huangxunleiutils.utils.CountingReqeustBody;
import com.xinkong.huangxunleiutils.utils.L;
import com.xinkong.huangxunleiutils.utils.ProgressHelper;
import com.xinkong.huangxunleiutils.utils.UIProgressResponseListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by 黄训磊 on 2017/1/7 0007 下午 11:39
 */


public class OkHttpNetActivity extends BaseActivity {
    @BindView(R.id.tv_content)
    TextView mTvContent;

    OkHttpClient okHttpClient;
    @BindView(R.id.img_show_result)
    ImageView mImgShowResult;
    //192.168.1.145
    // private String mBaseUrl = "http://192.70.6.100:8080/struts2-demo1/";
    private String mBaseUrl = "http://192.168.1.145:8080/struts2-demo1/";

    @Override
    public int getLayoutId() {
        return R.layout.activity_okhttp_net;
    }

    /**
     *
     */
    public void UIDownLoad(View view) {

//这个是非ui线程回调，不可直接操作UI
        final ProgressResponseListener progressResponseListener = new ProgressResponseListener() {
            @Override
            public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
                Log.e("TAG", "bytesRead:" + bytesRead);
                Log.e("TAG", "contentLength:" + contentLength);
                Log.e("TAG", "done:" + done);
                if (contentLength != -1) {
                    //长度未知的情况下回返回-1
                    Log.e("TAG", (100 * bytesRead) / contentLength + "% done");
                }
                Log.e("TAG", "================================");
            }
        };
        //这个是ui线程回调，可直接操作UI
        final UIProgressResponseListener uiProgressResponseListener = new UIProgressResponseListener() {
            @Override
            public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) {
                Log.e("TAG", "bytesRead:" + bytesRead);
                Log.e("TAG", "contentLength:" + contentLength);
                Log.e("TAG", "done:" + done);
                if (contentLength != -1) {
                    //长度未知的情况下回返回-1
                    Log.e("TAG", (100 * bytesRead) / contentLength + "% done");
                }
                Log.e("TAG", "================================");
                //ui层回调
                // downloadProgeress.setProgress((int) ((100 * bytesRead) / contentLength));
                //Toast.makeText(getApplicationContext(), bytesRead + " " +
                // contentLength + " " + done, Toast.LENGTH_LONG).show();
            }
        };

        //构造请求
        final Request request1 = new Request.Builder()
                .url(mBaseUrl + "girl111.jpg")
                .build();

        ProgressHelper.addProgressResponseListener(okHttpClient, uiProgressResponseListener).newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("TAG", "error ", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("TAG", response.body().string());
            }
        });
    }


    /**
     * 下载图片
     *
     * @param view
     */
    public void downLoad(View view) {

        Request.Builder builder = new Request.Builder();
        final Request request = builder.get().url(mBaseUrl + "girl111.jpg").build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                L.e("onFailure" + e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                L.e("onResponse");

                final Long total = response.body().contentLength();
                Long sum = 0L;
                InputStream inputStream = response.body().byteStream();
//                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//                if (bitmap != null) {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            mImgShowResult.setImageBitmap(bitmap);
//                        }
//                    });
//                }
                int len = 0;
                File file = new File(Environment.getExternalStorageDirectory(), "hello123.jpg");
                FileOutputStream fop = new FileOutputStream(file);
                byte[] buf = new byte[128];
                while ((len = inputStream.read(buf)) != -1) {
                    fop.write(buf, 0, len);
                    sum += len;
                    L.e(sum + "/" + total);
                    final Long finalSum = sum;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTvContent.setText(finalSum + "/" + total);
                        }
                    });
                }
                fop.flush();
                fop.close();
                inputStream.close();
                L.e("success ");


            }
        });

        // Picasso.with(this).load(mBaseUrl + "girl1.jpg").into(mImgShowResult);

    }

    /**
     * 上传图片
     *
     * @param view
     */
    public void upLoad(View view) {

        File file = new File(Environment.getExternalStorageDirectory(), "girl1.jpg");
        if (!file.exists()) {
            L.e(file.getAbsolutePath() + "文件不存在");
            return;
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"),
                file);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody body = builder.setType(MultipartBody.FORM)
                .addFormDataPart("userName", "张三")//
                .addFormDataPart("password", "12313")//
                .addFormDataPart("mPhoto", "hello.jpg", requestBody)
                .build();
        CountingReqeustBody countingReqeustBody = new CountingReqeustBody(body, new CountingReqeustBody.Listener() {
            @Override
            public void onReqeustProgress(Long byteWritten, Long contentLength) {
                L.e(byteWritten + "  /  " + contentLength);
            }
        });

        // mine type 对照表   参考http://tool.oschina.net/commons
        Request.Builder builder1 = new Request.Builder();
        Request request = builder1.url(mBaseUrl + "unLoadInfo").post(countingReqeustBody).build();
        excuteRequest(request);
    }

    /**
     * post 提交file
     *
     * @param view
     */
    public void doPostFile(View view) {


        File file = new File(Environment.getExternalStorageDirectory(), "girl1.jpg");
        if (!file.exists()) {
            L.e(file.getAbsolutePath() + "文件不存在");
            return;
        }
        // mine type 对照表   参考http://tool.oschina.net/commons
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"),
                file);
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(mBaseUrl + "doPostFile").post(requestBody).build();
        excuteRequest(request);

    }

    /**
     * post 提交 json数据
     *
     * @param view
     */
    public void doPostString(View view) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;chaset=utf-8"),
                "{userName:hello,password:123}");
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(mBaseUrl + "doPostString").post(requestBody).build();
        excuteRequest(request);

    }

    /**
     * post请求
     *
     * @param view
     */
    public void doPost(View view) {

        //FormEnCodingBuilder 在okhttp3.0 被替换为FormBody.Builder
        FormBody.Builder requestBodyBuilder = new FormBody.Builder();

        RequestBody requestBody = requestBodyBuilder.add("userName", "hello").add("password", "12314").build();

        Request.Builder builder = new Request.Builder();
        Request request = builder.url(mBaseUrl + "hello").post(requestBody).build();
        excuteRequest(request);
    }

    /**
     * get请求
     *
     * @param view
     */
    public void doGet(View view) {

        Request.Builder builder = new Request.Builder();

        Request request = builder.get().url(mBaseUrl + "hello?userName=sasada&&password=414231").build();

        excuteRequest(request);
    }

    private void excuteRequest(Request request) {
        Call call = okHttpClient.newCall(request);
        //call.execute();
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                L.e("onFailure" + e.getMessage());
                e.printStackTrace();

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                L.e("onResponse");
                final String msg = response.body().string();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTvContent.setText(msg);
                    }
                });
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        getPermissionToReadUserContacts();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(1000, TimeUnit.MINUTES);
        builder.readTimeout(1000, TimeUnit.MINUTES);
        builder.writeTimeout(1000, TimeUnit.MINUTES);

        builder.cookieJar(new CookieJar() {

            private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();

            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                cookieStore.put(url.host(), cookies);
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url.host());
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        });
        okHttpClient = builder.build();

    }

    //定义请求
    private static final int READ_CONTACTS_REQUEST = 1;

    //当用户执行的操作需要权限时候进行询问
    public void getPermissionToReadUserContacts() {
        /**
         * 1)使用ContextCompat.chefkSelfPermission(),因为Context.permission
         * 只在棒棒糖系统中使用
         * 2）总是检查权限（即使权限被授予）因为用户可能会在设置中移除你的权限*/
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //权限为获取，检查用户是否被询问过并且拒绝了，如果是这样的话，给予更多
            //解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                //在界面上展示为什么需要读取联系人
                Toast.makeText(this, "需要读取联系人和调用摄像头才能正常工作", Toast.LENGTH_SHORT).show();
            }
            //发起请求获得用户许可,可以在此请求多个权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION},
                    READ_CONTACTS_REQUEST);
        }
    }


    //从requestPermissions()方法回调结果


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //确保是我们的请求
        if (requestCode == READ_CONTACTS_REQUEST) {
            if (grantResults.length == 3 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "读取联系人权限获得", Toast.LENGTH_SHORT).show();

            } else if (grantResults.length == 3 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "读取联系人失败", Toast.LENGTH_SHORT).show();
            } else if (grantResults.length == 3 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "获取摄像头权限成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "获得摄像头权限失败", Toast.LENGTH_SHORT).show();
            }

        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

}